<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="null">
    <meta name="keyword" content="null">
    <meta name="theme-color" content="#600090">
    <meta name="msapplication-navbutton-color" content="#600090">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#600090">
    <link rel="shortcut icon" href="/assets/favicon.ico">
    <link rel="alternate" type="application/atom+xml" title="张小阳" href="/atom.xml">
    <link rel="stylesheet" href="https://cdn.bootcss.com/animate.css/3.5.2/animate.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css">
    <title>
        
        移动端判断横竖屏｜MillZhang&#39;s blog
        
    </title>

    <link rel="canonical" href="http://millzhang.github.io/2017/03/13/2017-note/01.移动端判断横竖屏/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/blog-style.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">
</head>

<!-- hack iOS CSS :active style -->
<body ontouchstart="" class="animated fadeIn">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "true" data-istags="false
" data-ishome = "false" >
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand animated pulse" href="/">
                <span class="brand-logo">
                    MillZhang
                </span>
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <!-- /.navbar-collapse -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/"><i class="fa fa-home"></i>主页</a>
                    </li>
                   <li>
                        <a href="/tags"><i class="fa fa-tags"></i>归档</a>
                    </li>
                    <li>
                        <a href="/about"><i class="fa fa-user"></i>关于</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
//    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>

<!-- Main Content -->

<!--only post-->

<header class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <div class="post-heading">
                    <h1>移动端判断横竖屏</h1>
                    
                    <span class="meta">
                         作者 MillZhang
                        <span>
                          日期 2017-03-13
                         </span>
                    </span>
                    <div class="tags text-center">
                        
                        <a class="tag" href="/tags/#mobile"
                           title="mobile">mobile</a>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="post-title-haojen">
        <span>
            移动端判断横竖屏
        </span>
    </div>
    <div class="post-header-image">
        
            <img src="http://oritfw5nq.bkt.clouddn.com/wall-303.jpg?imageView2/0/format/jpg/interlace/1/q/85|watermark/2/text/QnkgTWlsbHpoYW5n/font/5b6u6L2v6ZuF6buR/fontsize/480/fill/I0ZERkRGRA==/dissolve/56/gravity/SouthEast/dx/10/dy/10|imageslim">
         
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
            <!-- Post Container -->
            <div class="col-lg-8 col-lg-offset-1 col-sm-9 post-container">
                <h3 id="CSS-Media-Queries"><a href="#CSS-Media-Queries" class="headerlink" title="CSS Media Queries"></a>CSS Media Queries</h3><p>通过媒体查询的方式我们根据横竖屏来适配不同的样式</p>
<p>1.内联样式<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">@media screen and (orientation:portrait) &#123;</div><div class="line">    //竖屏</div><div class="line">&#125;</div><div class="line">@media screen and (orientation:landscape) &#123;</div><div class="line">    //横屏</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>2.外联样式<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&lt;!-- 竖屏 --&gt;</div><div class="line">&lt;link rel="stylesheet" media="all and (orientation:portrait)" href="..." /&gt;</div><div class="line">&lt;!-- 横屏 --&gt;</div><div class="line">&lt;link rel="stylesheet" media="all and (orientation:landscape)" href="..." /&gt;</div></pre></td></tr></table></figure></p>
<h3 id="window-matchMedia"><a href="#window-matchMedia" class="headerlink" title="window.matchMedia()"></a>window.matchMedia()</h3><p>除此之外，<a href="https://www.w3.org/TR/cssom-view-1/#dom-window-matchmedia" target="_blank" rel="external">CSS Object Model（CSSOM）Views</a> 规范增加了对 JavaScript 操作 CSS Media Queries 的原生支持，它在 window 对象下增加了 matchMedia() 方法，让我们能够通过脚本的方式来实现媒体查询。</p>
<p>window.matchMedia() 方法接受一个 Media Queries 语句的字符串作为参数，返回一个 MediaQueryList 对象。该对象有 media 和 matches 两个属性：</p>
<ul>
<li>media：返回所查询的 Media Queries 语句字符串</li>
<li>matches：返回一个布尔值，表示当前环境是否匹配查询语句</li>
</ul>
<p>同时，它还包含了两个方法，用来监听事件：</p>
<ul>
<li>addListener(callback)：绑定回调 callback 函数</li>
<li>removeListener(callback)：注销回调 callback 函数</li>
</ul>
<p>那么，通过 window.matchMedia() 的方法，我们可以这样判断横竖屏：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> mql = <span class="built_in">window</span>.matchMedia(<span class="string">"(orientation: portrait)"</span>);</div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">onMatchMeidaChange</span>(<span class="params">mql</span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span>(mql.matches) &#123;</div><div class="line">        <span class="comment">// 竖屏</span></div><div class="line">    &#125;<span class="keyword">else</span> &#123;</div><div class="line">        <span class="comment">// 横屏</span></div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">onMatchMeidaChange(mql);</div><div class="line">mql.addListener(onMatchMeidaChange);</div></pre></td></tr></table></figure></p>
<h3 id="window-innerHeight-window-innerWidth"><a href="#window-innerHeight-window-innerWidth" class="headerlink" title="window.innerHeight/window.innerWidth"></a>window.innerHeight/window.innerWidth</h3><p>在 CSS Media Queries 中，Orientation 属性有两个值：</p>
<ul>
<li>portrait，指的是当 height 大于等于 width 的情况</li>
<li>landscape，指的是当 height 小于 width 的情况</li>
</ul>
<p>所以，还有一种最为常见的方法是通过比较页面的宽高，当页面的高大于等于宽时则认为是竖屏，反之则为横屏。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">detectOrient</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span>(<span class="built_in">window</span>.innerHeight &gt;= <span class="built_in">window</span>.innerWidth) &#123;</div><div class="line">        <span class="comment">// 竖屏</span></div><div class="line">    &#125;<span class="keyword">else</span> &#123;</div><div class="line">        <span class="comment">// 横屏</span></div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">detectOrient();</div><div class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>,detectOrient);</div></pre></td></tr></table></figure>
<h3 id="window-orientation"><a href="#window-orientation" class="headerlink" title="window.orientation"></a>window.orientation</h3><p>在 iOS 平台以及大部分 Android 手机都有支持 <code>window.orientation</code> 这个属性，它返回一个与默认屏幕方向偏离的角度值：</p>
<ul>
<li>0：代表此时是默认屏幕方向</li>
<li>90：代表顺时针偏离默认屏幕方向90度</li>
<li>-90：代表逆时针偏离默认屏幕方向90度</li>
<li>180：代表偏离默认屏幕方向180度</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">switch</span>(<span class="built_in">window</span>.orientation) &#123;</div><div class="line">    <span class="keyword">case</span> <span class="number">0</span>:</div><div class="line">        displayStr += <span class="string">"Portrait"</span>;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> <span class="number">-90</span>:</div><div class="line">        displayStr += <span class="string">"Landscape (right, screen turned clockwise)"</span>;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> <span class="number">90</span>:</div><div class="line">        displayStr += <span class="string">"Landscape (left, screen turned counterclockwise)"</span>;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> <span class="number">180</span>:</div><div class="line">        displayStr += <span class="string">"Portrait (upside-down portrait)"</span>;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><img src="https://misc.aotu.io/Tingglelaoo/iPhone-orientation.png" alt="例图"></p>
<p>在实际应用中，对于 iPhone 和大部分 Android 是没有180度的手机竖屏翻转的情况的，但是 iPad 是存在的。所以，简化下代码，我们可以绑定orientationchange事件来判断横竖屏：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">detectOrient</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span> (<span class="built_in">Math</span>.abs(<span class="built_in">window</span>.orientation) === <span class="number">90</span>) &#123;</div><div class="line">        <span class="comment">// 横屏</span></div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="comment">// 竖屏</span></div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">detectOrient();</div><div class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'orientationchange'</span>,detectOrient);</div></pre></td></tr></table></figure>
<h3 id="影响判断的问题"><a href="#影响判断的问题" class="headerlink" title="影响判断的问题"></a>影响判断的问题</h3><ul>
<li>window.orientation属性值不一致(IOS相同,Android不一定一致哦)</li>
<li>软键盘的弹出(Android情况下,软件盘的弹出会引起页面的收缩)</li>
</ul>
<h3 id="最佳实现方式"><a href="#最佳实现方式" class="headerlink" title="最佳实现方式"></a>最佳实现方式</h3><p>假如屏幕分辨率固定值为：screen.width 和 screen.height（需要注意，这里很重要的一点是：在移动端，屏幕翻转时，screen.width 和 screen.height 的值依然是不变的）</p>
<ul>
<li>若获取 当前页面的宽（document.documentElement.clientWidth），等于屏幕分辨率的宽(screen.width)，则可认定当前属于竖屏。</li>
<li>若获取 当前页面的宽（document.documentElement.clientWidth），等于屏幕分辨率的高(screen.height)，则可认定当前属于横屏。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">detectOrient</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> storage = localStorage;</div><div class="line">    <span class="keyword">var</span> data = storage.getItem(<span class="string">'J-recordOrientX'</span>);</div><div class="line">    <span class="keyword">var</span> w = <span class="built_in">document</span>.documentElement.clientWidth,</div><div class="line">        h = <span class="built_in">document</span>.documentElement.clientHeight;</div><div class="line">    <span class="keyword">var</span> _Width = <span class="number">0</span>,</div><div class="line">        _Height = <span class="number">0</span>;</div><div class="line">    <span class="keyword">if</span>(!data) &#123;</div><div class="line">        _Width = <span class="built_in">window</span>.screen.width;</div><div class="line">        _Height = <span class="built_in">window</span>.screen.height;</div><div class="line">        storage.setItem(<span class="string">'J-recordOrientX'</span>,_Width + <span class="string">','</span> + _Height);</div><div class="line">    &#125;<span class="keyword">else</span> &#123;</div><div class="line">        <span class="keyword">var</span> str = data.split(<span class="string">','</span>);</div><div class="line">        _Width = str[<span class="number">0</span>];</div><div class="line">        _Height = str[<span class="number">1</span>];</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span>(w == _Width) &#123;</div><div class="line">        <span class="comment">// 竖屏</span></div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span>(w == _Height)&#123;</div><div class="line">        <span class="comment">// 横屏</span></div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">detectOrient();</div><div class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'resize'</span>,detectOrient);</div></pre></td></tr></table></figure>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><ul>
<li><a href="https://aotu.io/notes/2017/01/31/detect-orientation/" target="_blank" rel="external">凹凸实验室</a></li>
<li><a href="https://www.w3.org/TR/screen-orientation/" target="_blank" rel="external">W3</a></li>
</ul>

                <hr>
                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2017/04/13/2017-note/02.移动端坑和解决方案/" data-toggle="tooltip" data-placement="top"
                           title="移动端的坑和解决方案">&larr; 上一页</a>
                    </li>
                    
                    
                </ul>
                <div class="comment">
                    <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
                </div>
            </div>
            <div class="hidden-xs col-sm-3 toc-col">
                <div class="toc-wrap">
                    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#CSS-Media-Queries"><span class="toc-text">CSS Media Queries</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#window-matchMedia"><span class="toc-text">window.matchMedia()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#window-innerHeight-window-innerWidth"><span class="toc-text">window.innerHeight/window.innerWidth</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#window-orientation"><span class="toc-text">window.orientation</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#影响判断的问题"><span class="toc-text">影响判断的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#最佳实现方式"><span class="toc-text">最佳实现方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#参考"><span class="toc-text">参考</span></a></li></ol>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                

                <!-- Friends Blog -->
                
            </div>
        </div>

    </div>
</article>
<!-- 网易云音乐-->

<iframe class="cloud-music" frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 
    src="//music.163.com/outchain/player?type=2&amp;id=18803411&amp;auto=0&amp;height=66">
</iframe>
<!-- 网易云跟帖-->
<script src="https://img1.cache.netease.com/f2e/tie/yun/sdk/loader.js"></script>
<script>
var cloudTieConfig = {
  url: document.location.href, 
  sourceId: "",
  productKey: "40a8ee22b6084862a8907e6902e525fa",
  target: "cloud-tie-wrapper"
};
var yunManualLoad = true;
Tie.loader("aHR0cHM6Ly9hcGkuZ2VudGllLjE2My5jb20vcGMvbGl2ZXNjcmlwdC5odG1s", true);
</script>

<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <p class="copyright text-muted">
                    Copyright &copy; MillZhang 2017
                    <br>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/blog.js"></script>

<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://oritfw5nq.bkt.clouddn.com/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>



<!--wechat title img-->
<img class="wechat-title-img" src="http://oritfw5nq.bkt.clouddn.com/avatar.jpg?imageslim">
<a id="backtop" class="border-bottom" href="javascript:;">回顶部</a>
<script type="application/javascript">
var docOuter = document.body.scrollTop ? document.body : document.documentElement;
var backToTop = function(rate) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  var top = function() {
    scrollTop = scrollTop + (0 - scrollTop) / (rate || 2);
    if (scrollTop < 1) {
      doc.scrollTop = 0;
      return;
    }
    doc.scrollTop = scrollTop;
    // 动画gogogo!
    requestAnimationFrame(top);
  };
  top();
};
var topBtn = document.getElementById('backtop'),
    docTop = docOuter.scrollTop;
if(docTop>=300){
  topBtn.style.opacity = 1;
}

topBtn.onclick = function() {
  backToTop(12)
}
window.onscroll = function(e) {
  var doc = document.body.scrollTop ? document.body : document.documentElement;
  var scrollTop = doc.scrollTop;
  if (scrollTop >= 300) {
    topBtn.style.opacity = 1;
  } else {
    topBtn.style.opacity = 0;
  }
}
</script>
</body>

</html>
